package com.tool4j.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;

import java.util.HashMap;
import java.util.Map;

public class MainReplyNode implements NodeAction {

    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        if (state.value("code_content").isPresent()) {
            Map<String, Object> result = new HashMap<>();
            String codeContent = state.value("code_content").get().toString();
            // 去除 Markdown code block
            codeContent = codeContent.trim();
            if (codeContent.startsWith("```java")) {
                codeContent = codeContent.replaceFirst("^```json", "").trim();
            }
            if (codeContent.startsWith("```")) {
                codeContent = codeContent.replaceFirst("^```", "").trim();
            }
            if (codeContent.endsWith("```")) {
                codeContent = codeContent.replaceAll("```$", "").trim();
            }
            return Map.of("format_code_content", codeContent);
        } else {
            return Map.of("format_code_content", "");
        }
    }
}
